﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TekaMUD.Engine.Framework;
using TekaMUD.Engine.Workers;
using System.Threading;
using System.Configuration;
using TekaMUD.Engine.Persistence;
using TekaMUD.Engine.ServerTasks;

namespace TekaMUD.Engine
{
	/// <summary>
	/// Engine entry point.
	/// </summary>
	public class Control
	{
		public static void Initialize(bool loadWorld)
		{
			if (loadWorld)
				Storage.LoadWorld();

			int tcpServerPort = int.Parse(ConfigurationManager.AppSettings["SERVER_TCP_PORT"]);

			// Register some workers.
			Supervisor.AddWorker(new WorkerThreadStorage(new TimeSpan(1, 0, 0)));
			Supervisor.AddWorker(new WorkerThreadCommandDispatcher());
			Supervisor.AddWorker(new WorkerThreadServerTasks());
			Supervisor.AddWorker(new WorkerThreadScheduler());
			Supervisor.AddWorker(new WorkerThreadNetworkServer(tcpServerPort));

			// Start threads.
			Supervisor.StartAll();

			// Add Repeatable tasks to the scheduler.
			SchedulerQueue.Insert(new RefreshNPCTask(), DateTime.Now.Ticks);
			SchedulerQueue.Insert(new UpdateWeatherTask(), DateTime.Now.Ticks);
			SchedulerQueue.Insert(new RefreshPlayerTask(), DateTime.Now.Ticks);
		}

		public static void Terminate()
		{
			Supervisor.SignalThreadsForTermination();

			// Give some time for the threads to close.
			Logger.LogInfo("Waiting for 5 seconds for thread termination.");
			Thread.Sleep(5000);


			Logger.LogInfo("Aborting all threads.");
			Supervisor.AbortThreads();
		}
	}
}
